package gestoremulte.pack;

import java.io.File;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;

import javax.crypto.NoSuchPaddingException;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;

import android.os.Bundle;
import android.os.Environment;
import android.os.Parcelable;
import android.telephony.TelephonyManager;
import android.util.Log;

import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

/*
 * Activity principale e schermata iniziale dell'app.
 */
public class MainActivity extends Activity {
    /** Called when the activity is first created. */
	
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        // crea le diverse directory se non sono già create appena si avvia
        // utile la prima volta che viene avviato il programma
        if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
            Log.d("MyApp", "No SDCARD");
		} else {
		    File directory = new File(Environment.getExternalStorageDirectory()+File.separator+"GestioneMulte");
		    directory.mkdirs();
		    File directoryPhoto = new File(Environment.getExternalStorageDirectory()+File.separator+"GestioneMulte"+File.separator+"Foto");
		    directoryPhoto.mkdirs();
		    File directoryFile = new File(Environment.getExternalStorageDirectory()+File.separator+"GestioneMulte"+File.separator+"Files");
		    directoryFile.mkdirs();
		    
		    File directoryVerbali = new File(Environment.getExternalStorageDirectory()+File.separator+"GestioneMulte"+File.separator+"Files"+ File.separator+"Verbali");
		    directoryVerbali.mkdirs();
		    
		    File directoryNotifiche = new File(Environment.getExternalStorageDirectory()+File.separator+"GestioneMulte"+File.separator+"Files"+ File.separator+"Notifiche");
		    directoryNotifiche.mkdirs();
		    
		    File directoryACIPRA = new File(Environment.getExternalStorageDirectory()+File.separator+"GestioneMulte"+File.separator+"Files"+ File.separator+"ACIPRA");
		    directoryACIPRA.mkdirs();
		    
		    File directorytemp = new File(Environment.getExternalStorageDirectory()+File.separator+"GestioneMulte"+File.separator+"Files"+ File.separator+"temp");
		    directorytemp.mkdirs();
		    
		   File listaNotificaVerbali = new File(Environment.getExternalStorageDirectory()+File.separator+"GestioneMulte"+File.separator+"Files"+ File.separator+"Lista");
		   
		   try {
			if (listaNotificaVerbali.createNewFile()){
				WriteReadElementoLista file = new WriteReadElementoLista();
				file.initialize();
			}
				
		   } catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		   }
		   
		}
        
        //il login offline viene subito mostrato
        CustomDialogLoginOffline dialog = new CustomDialogLoginOffline(this);
        dialog.setCancelable(false);
        dialog.show();
        
        Button effettuamulta =(Button) findViewById(R.id.effettuamulta);
        effettuamulta.setOnClickListener(buttoneffettuaMultaListener);
        
        Button pagamento =(Button) findViewById(R.id.pagamento);
        pagamento.setOnClickListener(buttonepagamentoListner);
        
        Button carica = (Button) findViewById(R.id.carica);
        carica.setOnClickListener(CaricaListner);
        
        TelephonyManager telephonyManager = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
        VariabiliCondiviseApplication.IMEI = telephonyManager.getDeviceId();
        

        
    }
    
    //Quando il telefono riparte viene ripreso l'IMEI e si riporta l'app in modalità offline
    protected void onRestart(){
    	super.onRestart();
    	
    	if (VariabiliCondiviseApplication.restored){
    		TelephonyManager telephonyManager = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
            VariabiliCondiviseApplication.IMEI = telephonyManager.getDeviceId();
            
    		VariabiliCondiviseApplication.online = false;
			
			CustomDialogLoginOffline dialog = new CustomDialogLoginOffline(this);
		    dialog.setCancelable(false);
		    dialog.show();
    	}
    }
    
    // viene creato il menu
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu, menu);
        return true;
    }
    
    // imposta cosa accade quando si seleziona un elemento del menu
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.icon: 
            	CustomDialogLoginOnline dialog = new CustomDialogLoginOnline(this);
            	dialog.show();
                break;
            case R.id.ricaricaVerbali:
            	/* dovrebbe connettersi al cloud e scaricare i verbali */
            	break;
           
            case R.id.ricaricafiletemp:
            	
            	final CharSequence[] items = {"Notifica", "Verbale"};

            	AlertDialog.Builder builder = new AlertDialog.Builder(this);
            	builder.setTitle("Seleziona file temporaneo");
            	builder.setItems(items, new DialogInterface.OnClickListener() {
            	    public void onClick(DialogInterface dialog, int item) {
            	        
            	    	if (items[item].equals("Notifica")){
            	        	EncryptionDecription encrdecr = new EncryptionDecription();
    					
	    					Notifica not = null;
	    					
	    					try {
	    						not = encrdecr.decryptLoadNotifica("",true);
	    					} catch (InvalidKeyException e) {
	    						// TODO Auto-generated catch block
	    						e.printStackTrace();
	    					} catch (NoSuchAlgorithmException e) {
	    						// TODO Auto-generated catch block
	    						e.printStackTrace();
	    					} catch (NoSuchPaddingException e) {
	    						// TODO Auto-generated catch block
	    						e.printStackTrace();
	    					} catch (IOException e) {
	    						// TODO Auto-generated catch block
	    						e.printStackTrace();
	    						
	    					} catch (ClassNotFoundException e) {
	    						// TODO Auto-generated catch block
	    						e.printStackTrace();
	    					}
	    					
	    					if (not != null){
	    						Intent i = new Intent(MainActivity.this,RiassuntoMultaActivity.class);
	    		                i.putExtra("targa", not.getTarga());
	    		                i.putExtra("via", not.getVia_comune());          	
	    		            	i.putExtra("data_ora", not.getData_ora());
	    		            	i.putExtra("sanzione", not.getSanzione());
	    		            	ArrayList<String> in = not.getDescrizioneInfrazione();
	    		            	ArrayList<String> co = not.getInfrazioni();
	    		            	String infrazioni ="";
	    		            	for (int f=0; f< in.size();f++)
	    		            		infrazioni += co.get(f)+ "-" + " " + in.get(f) + "\n";
	    		            	
	    		            	
	    		            	i.putStringArrayListExtra("infraz", not.getDescrizioneInfrazione());
	    		            	i.putStringArrayListExtra("cod", not.getInfrazioni());
	    		            	i.putExtra("infrazioni", infrazioni);
	    		            	i.putExtra("nverbale", not.getVerbaleNumber());
	    		            	i.putExtra("lat", not.getLat());
	    		            	i.putExtra("lon", not.getLon());
	    		            	i.putExtra("fromDB", true);
	    		            	
	    		            	
	    		            	startActivity(i);
	    					}
	    					
	    					else
	    						Toast.makeText(MainActivity.this, "Non esiste alcun file temporaneo relativo alla notifica",
	    								 Toast.LENGTH_SHORT).show();
    					}
            	    	
            	    	else if (items[item].equals("Verbale")){
            	    		
            	    		EncryptionDecription encrdecr = new EncryptionDecription();
        					Verbale v = null;
        					try {
        						v = encrdecr.decryptLoadVerbale("",true);
        					} catch (InvalidKeyException e) {
        						// TODO Auto-generated catch block
        						e.printStackTrace();
        						
        					} catch (NoSuchAlgorithmException e) {
        						// TODO Auto-generated catch block
        						e.printStackTrace();
        						
        					} catch (NoSuchPaddingException e) {
        						// TODO Auto-generated catch block
        						e.printStackTrace();
        						
        					} catch (IOException e) {
        						// TODO Auto-generated catch block
        						e.printStackTrace();
        						
        					} catch (ClassNotFoundException e) {
        						// TODO Auto-generated catch block
        						e.printStackTrace();
        						
        					}
        					
        					if (v!= null){
        						Intent i = new Intent(MainActivity.this,VerbaleActivity.class);
        						i.putExtra("verbale",(Parcelable) v);
        						i.putExtra("fromDB", true);
        						
        						
        		            	startActivity(i);
        					}
        					else
        						Toast.makeText(MainActivity.this, "Non esiste alcun file temporaneo relativo al Verbale",
	    								 Toast.LENGTH_SHORT).show();
            	    	}
            	    }
            	});
            	
            	AlertDialog alert = builder.create();
            	alert.show();
            	break;
        }
        return true;
    }
    
    // si avvia l'activity TargaActivity
    private OnClickListener buttoneffettuaMultaListener = new OnClickListener() {
        public void onClick(View v) {
        	VariabiliCondiviseApplication.fotoScattata = false;
        	startActivity(new Intent(MainActivity.this,TargaActivity.class ));
        }
    };
    
    // per il momento inserisce i verbali nel db, nn fa ancora nulla
    private OnClickListener buttonepagamentoListner = new OnClickListener() {
        public void onClick(View v) {
        	
        /* Ancora da implementare */
            
        }
    };
    
    // Si avvia l'activity che si occupa del caricamento dei verbali-notifiche
    private OnClickListener CaricaListner = new OnClickListener() {
        public void onClick(View v) {
        	
        	
        	startActivity(new Intent(MainActivity.this,CaricaNotificaVerbaleSecureActivity.class ));
        	
        }
    };
   
    
    
    
}